import javax.ws.rs.core.GenericType;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.JsonPrimitive;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import {{invokerPackage}}.JSON;

{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}}
public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} {
    private static final Logger log = Logger.getLogger({{classname}}.class.getName());

    public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
        @SuppressWarnings("unchecked")
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            if (!{{classname}}.class.isAssignableFrom(type.getRawType())) {
                return null; // this class only serializes '{{classname}}' and its subtypes
            }
            final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
            {{#oneOf}}
            final TypeAdapter<{{.}}> adapter{{.}} = gson.getDelegateAdapter(this, TypeToken.get({{.}}.class));
            {{/oneOf}}

            return (TypeAdapter<T>) new TypeAdapter<{{classname}}>() {
                @Override
                public void write(JsonWriter out, {{classname}} value) throws IOException {
                    if (value == null || value.getActualInstance() == null) {
                        elementAdapter.write(out, null);
                        return;
                    }

                    {{#oneOf}}
                    // check if the actual instance is of the type `{{.}}`
                    if (value.getActualInstance() instanceof {{.}}) {
                        JsonObject obj = adapter{{.}}.toJsonTree(({{.}})value.getActualInstance()).getAsJsonObject();
                        elementAdapter.write(out, obj);
                        return;
                    }

                    {{/oneOf}}
                    throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}");
                }

                @Override
                public {{classname}} read(JsonReader in) throws IOException {
                    Object deserialized = null;
                    JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();

                    {{#useOneOfDiscriminatorLookup}}
                    {{#discriminator}}
                    // use discriminator value for faster oneOf lookup
                    {{classname}} new{{classname}} = new {{classname}}();
                    String discriminatorValue = elementAdapter.read(in).getAsJsonObject().get("{{{propertyBaseName}}}").getAsString();
                    switch (discriminatorValue) {
                    {{#mappedModels}}
                        case "{{{mappingName}}}":
                            deserialized = adapter{{modelName}}.fromJsonTree(jsonObject);
                            new{{classname}}.setActualInstance(deserialized);
                            return new{{classname}};
                    {{/mappedModels}}
                        default:
                            log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue));
                    }

                    {{/discriminator}}
                    {{/useOneOfDiscriminatorLookup}}
                    int match = 0;

                    {{#oneOf}}
                    // deserialize {{{.}}}
                    try {
                        deserialized = adapter{{.}}.fromJsonTree(jsonObject);
                        match++;
                        log.log(Level.FINER, "Input data matches schema '{{{.}}}'");
                    } catch (Exception e) {
                        // deserialization failed, continue
                        log.log(Level.FINER, "Input data does not match schema '{{{.}}}'", e);
                    }

                    {{/oneOf}}
                    if (match == 1) {
                        {{classname}} ret = new {{classname}}();
                        ret.setActualInstance(deserialized);
                        return ret;
                    }

                    throw new IOException(String.format("Failed deserialization for {{classname}}: %d classes match result, expected 1. JSON: %s", match, jsonObject.toString()));
                }
            }.nullSafe();
        }
    }

    // store a list of schema names defined in oneOf
    public static final Map<String, GenericType> schemas = new HashMap<String, GenericType>();

    public {{classname}}() {
        super("oneOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}});
    }

    {{#oneOf}}
    public {{classname}}({{{.}}} o) {
        super("oneOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}});
        setActualInstance(o);
    }

    {{/oneOf}}
    static {
        {{#oneOf}}
        schemas.put("{{{.}}}", new GenericType<{{{.}}}>() {
        });
        {{/oneOf}}
    }

    @Override
    public Map<String, GenericType> getSchemas() {
        return {{classname}}.schemas;
    }

    /**
     * Set the instance that matches the oneOf child schema, check
     * the instance parameter is valid against the oneOf child schemas:
     * {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}
     *
     * It could be an instance of the 'oneOf' schemas.
     * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf).
     */
    @Override
    public void setActualInstance(Object instance) {
        {{#isNullable}}
        if (instance == null) {
           super.setActualInstance(instance);
           return;
        }

        {{/isNullable}}
        {{#oneOf}}
        if (instance instanceof {{{.}}}) {
            super.setActualInstance(instance);
            return;
        }

        {{/oneOf}}
        throw new RuntimeException("Invalid instance type. Must be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}");
    }

    /**
     * Get the actual instance, which can be the following:
     * {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}
     *
     * @return The actual instance ({{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}})
     */
    @Override
    public Object getActualInstance() {
        return super.getActualInstance();
    }

    {{#oneOf}}
    /**
     * Get the actual instance of `{{{.}}}`. If the actual instance is not `{{{.}}}`,
     * the ClassCastException will be thrown.
     *
     * @return The actual instance of `{{{.}}}`
     * @throws ClassCastException if the instance is not `{{{.}}}`
     */
    public {{{.}}} get{{{.}}}() throws ClassCastException {
        return ({{{.}}})super.getActualInstance();
    }

    {{/oneOf}}
}
